<?php

namespace App\Service\users;

use App\Models\users\UsersAmountRecordModel;
use App\Models\users\UsersModel;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use lxs\config\BaseStatic;

class UsersService extends BaseStatic
{

    // 获取用户信息
    public function getUserInfo($uid) {
        return UsersModel::where('id', $uid)->first();
    }


    /**
     * 获取用户详细信息
     */
    public function getUserDetail($uid) {
        $userInfo = UsersModel::with(['userBank', 'userSetting'])->where('id', $uid)->first();
        return $userInfo;
    }


    /**
     * 用户金额记录表
     * @param int $uid
     * @param float $num
     * @param string $type
     * @param string $remark
     * @param string $operator
     * @return bool
     * @throws Exception
     */
    public function amountRecord(int $uid, float $num, string $type, string $remark, string $operator): bool
    {

        if ($num == 0) return false;

        $userInfo = self::getUserInfo($uid);
        $amount = $userInfo->amount;

        if (($credit = $amount + $num) < 0) {
            throw new Exception('输入数值有误!');
        }

        $credit = max(0, $amount + $num);

        $data = [
            'uid' => $uid,
            'num' => $num,
            'type' => $type,
            'operator' => $operator,
            'remark' => $remark,
            'credits' => $credit,
            'create_time' => time()
        ];

        try {
            DB::beginTransaction();

            UsersAmountRecordModel::insert($data);
            UsersModel::where('id', $uid)->update(['amount' => $credit]);

            DB::commit();
            return true;
        } catch (\Throwable $e) {
            Log::error('插入用户金额记录表异常：' . $e->getMessage() . $e->getLine());
            return false;
        }
    }


}
